import java.io.IOException;
import java.io.BufferedReader;
import java.io.PrintStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.StringTokenizer;
import java.util.HashMap;
import java.util.Random;

public class Server{
    
    private static class Pair {
        public int secretNo;
        public int guessNo; //guess number 1,2,3 etc
        Pair(int sNo, int gNo) {
            secretNo = sNo;
            guessNo = gNo;
        }
    }
    
    private static HashMap<String, Pair> map = new HashMap<String, Pair>();
    
    public static void main(String[] args) throws IOException{
        System.out.println("Creating Server socket");
        ServerSocket ss = new ServerSocket(8080);
        int numGuesses = 0;
        int guessedNr = 0;
        int uniqId = 0;
        String cookie = "";
        String responseStr = "";
        boolean setCookie = true;
        Random rand = new Random();
        int correctNr = 0;
        while(true){
            System.out.println("Waiting for client...");
            Socket s = ss.accept();
            System.out.println("Client connected");
            BufferedReader request = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String str = request.readLine();
            StringTokenizer tokens = new StringTokenizer(str," ");
            tokens.nextToken(); // Ordet GET
            String requestedDocument = tokens.nextToken();
            System.out.println("requested doc: " + requestedDocument);
            PrintStream response = new PrintStream(s.getOutputStream());
            response.println("HTTP/1.1 200 OK");
            response.println("Server : craptastic");
            response.println("Content-Type: text/html; charset=utf-8");
            try {
                if(requestedDocument.length() >= 8)
                    guessedNr = Integer.parseInt(requestedDocument.substring(8)); //the guessed nr is after the /? in the request
                while( (str = request.readLine()) != null && str.length() > 0){
                    if(str.split(":")[0].equals("Cookie")){
                        cookie = str.split(":")[1].trim(); //the cookie field
                        if(!map.containsKey(cookie)){ //new visitor
                            setCookie = true; //new visitor set cookie
							correctNr = rand.nextInt(100) + 1; //1-100
                            map.put("sessionId=" + (++uniqId), new Pair(correctNr, 0));
                            numGuesses = 0;
                        }else{
                            setCookie = false;
                            Pair p = map.get(cookie);
							//System.out.println("pair: "+p.secretNo+" "+p.guessNo);
                            map.put(cookie, new Pair(p.secretNo, p.guessNo + 1));  
                            correctNr = p.secretNo; //update the correct no to the one from the map
                            numGuesses = p.guessNo + 1;
                        }
                        //System.out.println(map);
                        
                    }
                }
                System.out.println("Request done.");
                s.shutdownInput();
                
                String hint = "";
                if(guessedNr > correctNr)
                    hint = "Nope, guess lower";
                else if(guessedNr < correctNr)
                    hint = "Nope, guess higher";
                else 
                    hint = "You won, congrats!";
                
                if(setCookie)
                    response.println("Set-Cookie: sessionId=" + uniqId + "; expires=Wednesday,31-Dec-12 21:00:00 GMT");
                
                response.println();
                
				if(setCookie)
					responseStr = "<html><head><title>Number Guess Game</title><script type = \"text/javascript\">function inputfocus(form){form.guess.focus()}</script></head><body onLoad=\"inputfocus(document.guessform);\"> Guess a number between 1 and 100<br> <form name=\"guessform\"><input type=text name=\"guess\"><input type=submit value=\"Guess\"></form></body></html>";
				else
					responseStr = "<html><head><title>Number Guess Game</title><script type = \"text/javascript\">function inputfocus(form){form.guess.focus()}</script></head><body onLoad=\"inputfocus(document.guessform);\">" + hint +"<br>" + numGuesses + "<br><form name=\"guessform\"><input type=text name=\"guess\"><input type=submit value=\"Guess\"></form></body></html>";
                response.println(responseStr);               
                response.println();
				guessedNr = 0;
            }catch(NumberFormatException e){                
                response.println("<h1>909</h1><p>Too much salt on the kebab.</p>");          
            }

            s.shutdownOutput();
            s.close();
        }
    }
}